package com.laoxu.demo.controller;

import com.laoxu.demo.entity.ResultBean;
import com.laoxu.demo.entity.User;
import com.laoxu.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:  用户controller
 * @Author laoxu
 * @Date 2019/12/21 10:11
 **/
@Api(description="用户管理")
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    UserService userService;

    @ApiOperation("根据ID查询用户")
    @GetMapping("/{id}")
    public ResultBean getOne(@ApiParam(name="id",value = "用户ID",required = true)
                                 @PathVariable Integer id){
        User user = userService.getById(id);
        ResultBean result = new ResultBean(0,"查询成功",1, user);

         return result;
    }

    @ApiOperation("分页查询")
    @GetMapping("/list")
    public ResultBean list(@ApiParam(name="页码",value = "page",required = false)
                           @RequestParam(defaultValue = "1") Integer page,
                           @ApiParam(name="页行数",value = "limit",required = false)
                           @RequestParam(defaultValue = "10") Integer limit){
        List<User> users = userService.getPager(page,limit);
        int count = userService.getAllUsers().size();

        ResultBean result = new ResultBean(0,"查询成功",count,users);

        return result;
    }

    @ApiOperation("修改用户")
    @PostMapping("/save")
    public ResultBean save(@ApiParam(name="用户实体",value = "user实体",required = true)
                           @RequestBody User user){
        // 判断是新增还是修改
        if(user.getId()==0){
            userService.addUser(user);
        }else{
            userService.updateUser(user);
        }

        return new ResultBean(200,"保存成功",0,"");
    }

    @ApiOperation("删除用户（多个）")
    @PostMapping("/remove")
    public ResultBean modify(@ApiParam(name="用户ID数组",value = "ids",required = true)
                                 @RequestBody int[] ids){
        userService.delUsers(ids);
        return new ResultBean(200,"删除成功",0,"");
    }
}
